package com.gdzl_hadoop.controller;

import com.gdzl_hadoop.common.ServerResponse;
import com.gdzl_hadoop.service.IDataHandleService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static com.gdzl_hadoop.util.FileUtil.getZIP;

@Controller()
@RequestMapping(value = "/file")
public class FileController {

    @Autowired
    private IDataHandleService iDataHandleService;

    /**
     * 下载shp地图文件
     *
     * @param servletRequest
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("download.do")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest servletRequest, String year, String xzqdm) throws Exception {
        String fileName = iDataHandleService.dowloadFile(xzqdm);//通过xzqdm字段数据库查找
        //    System.out.println(fileName);
        if (fileName != null) {
            String pathRoot = servletRequest.getSession().getServletContext().getRealPath("") + "\\upFileDir\\" + year + File.pathSeparator + xzqdm;
            File file = new File(pathRoot + File.separator + fileName);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } else
            return null;
    }

    /**
     * 打包下载文件夹
     *
     * @param servletRequest
     * @param year 年份
     * @param xzqdm 行政区代码
     * @return
     * @throws IOException
     */
    @RequestMapping("batdownload.do")
    public ResponseEntity<byte[]> batDownload(HttpServletRequest servletRequest, String year, String xzqdm) throws IOException {
        String pathRoot = servletRequest.getSession().getServletContext().getRealPath("") + "\\upFileDir\\" + year + "\\" + xzqdm;
        String zipPathRoot = servletRequest.getSession().getServletContext().getRealPath("") + "\\zip\\" + year + "\\" + xzqdm;
        String zipName = year + "-" + xzqdm + ".zip";
        File zip = getZIP(pathRoot, zipName, zipPathRoot);
        if (zip != null) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", zip.getName());
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(FileUtils.readFileToByteArray(zip), headers, HttpStatus.OK);
        } else
            return null;
    }

    /**
     * 上传shp地图文件
     *
     * @param servletRequest
     * @param files          文件
     * @param year           年份
     * @param xzqdm          行政区代码
     * @return 成功:  {status:0, msg:"文件上传成功"}   失败: {status:1, msg:"文件上传失败"}
     * @throws IOException
     */
    @RequestMapping(value = "upload.do")
    @ResponseBody
    public ServerResponse<String> uploadShp(HttpServletRequest servletRequest, @RequestParam(value = "files", required = false) MultipartFile[] files, String year, String xzqdm) {

        if (files.length > 0 && iDataHandleService.checkFileExist(xzqdm, year) > 0) {
            return ServerResponse.createByErrorMessage("文件已经存在！");
        }
        //如果文件内容不为空，则写入上传路径
        String pathRoot = servletRequest.getSession().getServletContext().getRealPath("") + "\\upFileDir\\" + year + File.separator + xzqdm;
        //System.out.println(pathRoot);
        // String path = "http://" + PropertiesUtil.getProperty("file.url") + "/upFileDir/" + year;//服务器端可读取的路径
        if (files.length > 0 && files != null) {
            List<Integer> temp = new ArrayList<>();
            for (MultipartFile file : files) {
                //上传文件名
                String filename = file.getOriginalFilename();
                File filepath = new File(pathRoot, filename);
                //System.out.println(filepath.getName()+" filepath");
                //判断路径是否存在，没有就创建一个
                if (!filepath.getParentFile().exists()) {
                    System.out.println("创建");
                    filepath.getParentFile().mkdirs();
                }
                //将上传文件保存到一个目标文档中
                File file1 = new File(pathRoot + File.separator + filename);
                try {
                    file.transferTo(file1);
                } catch (IOException e) {
                    return ServerResponse.createByErrorMessage("文件上传失败");
                }
                String tempName = file1.getName();
                if (tempName.substring(tempName.lastIndexOf(".") + 1).equals("shp")) {
                    temp.add(iDataHandleService.insertFileRecord(tempName, pathRoot + File.separator + tempName, xzqdm, year));
                }

            }

            //     System.out.println(file1.getPath());
            if (!temp.contains(0))
                return ServerResponse.createBySuccessMessage("文件上传成功");
        }
        return ServerResponse.createByErrorMessage("文件上传失败");
    }
}